import {
  reqGetAddressList,
  reqDelAddress
} from '../../../api/address'

Page({
  // 页面的初始数据
  data: {
    addressList: []
  },
  onLoad(option) {
    // 传递参数，是从订单页面过来的，其他页面不做选择地址处理
    const {
      isFormOrderPage
    } = option
    this.isFormOrderPage = isFormOrderPage
  },
  onShow() {
    this.reqGetAddressList()
  },
  // 获取收货地址列表
  async reqGetAddressList() {
    const {
      code,
      data
    } = await reqGetAddressList()
    if (code === 200) {
      this.setData({
        addressList: data
      })
    }
    console.log(data, 'reqGetAddressList');
  },
  // 去编辑页面
  toEdit(event) {
    const {
      id
    } = event.target.dataset
    wx.navigateTo({
      url: `/modules/settingModule/pages/address/add/index?id=${id}`
    })
  },
  // 删除地址
  async deleteAddress(event) {
    const {
      id
    } = event.target.dataset
    const {
      code,
      message
    } = await reqDelAddress(id)
    if (code === 200) {
      wx.flowerTipToast({
        title: message,
        icon: 'success'
      })
      this.reqGetAddressList()
    }
  },
  // 选择收货地址
  selectAddress(event) {
    if (this.isFormOrderPage != 1) return
    const {
      address
    } = event.currentTarget.dataset
    const app = getApp()
    app.globalData.address = address
    wx.navigateBack()
  }
})